package com.pomelo.chat.controller;

import com.pomelo.chat.config.ChatConfig;
import com.pomelo.chat.config.ChatGPTConfig;
import com.pomelo.chat.domain.Chat;
import com.pomelo.chat.exception.ChatException;
import com.pomelo.chat.service.ChatGPTService;
import com.pomelo.chat.service.ChatService;
import com.pomelo.chat.util.*;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/open-ai")
public class ChatController {

    Logger logger = LoggerFactory.getLogger(ChatController.class);


    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ChatGPTService chatService;


    @GetMapping("/test")
    public AjaxResult test() {
        return AjaxResult.success("test");
    }


    @GetMapping("/token")
    public AjaxResult getToken() {
        return AjaxResult.success(Common.createUUID());
    }

    /**
     * 开始对话
     *
     * @return 响应结果实体
     */
    @PostMapping("/ask")
    public AjaxResult chatGPT3(@RequestBody Question question,
                               @RequestHeader(name = "token", required = false) String token,
                               BindingResult bindingResult,
                               HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            return AjaxResult.failure(bindingResult.getAllErrors().get(0).toString());
        }
        //if (!ObjectUtils.isEmpty(question.getIsContinue()) && question.getIsContinue()) { // 连续问答
        //    if (StringUtils.hasLength(token)) {
        //        Object o = redisTemplate.opsForValue().get(Constant.MSG_PREFIX + token);
        //        question.setQ(o.toString());
        //    }
        //}
        Chat chat = chatService.askGPT3(question, request);
        if (chat.getIsEnd()) {
            //token = StringUtils.hasLength(token) ? token : Common.createUUID();
            //redisTemplate.opsForValue().set(Constant.MSG_PREFIX + token, chat.getAnswer(), 30, TimeUnit.MINUTES);
        }

        //chatResult.setToken(token);
        return AjaxResult.success(chat);
    }

}
